﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;

using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.ADF.BaseClasses;

namespace SZ
{
    public partial class AttributeTable : DevExpress.XtraEditors.XtraForm
    {
        public IMapControl3 m_mapControl;
        public ILayer m_Layer;
        public DataTable attributeTable;

        //构造函数
        public AttributeTable(IMapControl3 mapControl, ILayer pLayer)
        {
            InitializeComponent();
            m_mapControl = mapControl;
            m_Layer = pLayer;

            CreateAttributeTable(pLayer);
        }

        //创建属性表
        public void CreateAttributeTable(ILayer player)
        {
            string tableName;
            tableName = getValidFeatureClassName(player.Name);
            attributeTable = CreateDataTable(player, tableName);
            this.gridControl1.DataSource = attributeTable;
            this.NameLable.Text = tableName;
            this.Text = "属性表[" + tableName + "] " + "记录数：" + attributeTable.Rows.Count.ToString();
            this.gridView1.BestFitColumns();//根据表格中的内容自动调整列宽（之前需要将OptionsView中的ColumnAutoWidth 设置为false）
        }

        //使名称合理
        public static string getValidFeatureClassName(string FCname)
        {
            int dot = FCname.IndexOf(".");
            if (dot != -1)
            {
                return FCname.Replace(".", "_");
            }
            return FCname;
        }

        //创建数据表
        public static DataTable CreateDataTable(ILayer pLayer, string tableName)
        {
            //创建空DataTable 
            DataTable pDataTable = CreateDataTableByLayer(pLayer, tableName);
            //取得图层类型 
            string shapeType = getShapeType(pLayer);
            //创建DataTable的行对象 
            DataRow pDataRow = null;
            //从ILayer查询到ITable 
            ITable pTable = pLayer as ITable;
            ICursor pCursor = pTable.Search(null, false);
            //取得ITable中的行信息 
            IRow pRow = pCursor.NextRow();
            while (pRow != null)
            {
                //新建DataTable的行对象 
                pDataRow = pDataTable.NewRow();
                for (int i = 0; i < pRow.Fields.FieldCount; i++)
                {
                    //如果字段类型为esriFieldTypeGeometry，则根据图层类型设置字段值 
                    if (pRow.Fields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        pDataRow[i] = shapeType;
                    }
                    //当图层类型为Anotation时，要素类中会有esriFieldTypeBlob类型的数据， 
                    //其存储的是标注内容，如此情况需将对应的字段值设置为Element 
                    else if (pRow.Fields.get_Field(i).Type == esriFieldType.esriFieldTypeBlob)
                    {
                        pDataRow[i] = "Element";
                    }
                    else
                    {
                        pDataRow[i] = pRow.get_Value(i);
                    }
                }
                //添加DataRow到DataTable 
                pDataTable.Rows.Add(pDataRow);
                pDataRow = null;
                pRow = pCursor.NextRow();
            }
            System.Runtime.InteropServices.Marshal.ReleaseComObject(pCursor);
            GC.Collect();
            GC.WaitForPendingFinalizers();

            return pDataTable;
        }

        //根据图层中各要素的属性创建数据表
        public static DataTable CreateDataTableByLayer(ILayer pLayer, string tableName)
        {
            //创建一个DataTable表 
            DataTable pDataTable = new DataTable(tableName);
            //取得ITable接口 
            ITable pTable = pLayer as ITable;
            IField pField = null;
            DataColumn pDataColumn;
            //根据每个字段的属性建立DataColumn对象 
            for (int i = 0; i < pTable.Fields.FieldCount; i++)
            {
                pField = pTable.Fields.get_Field(i);
                //新建一个DataColumn并设置其属性 
                pDataColumn = new DataColumn(pField.Name);
                if (pField.Name == pTable.OIDFieldName)
                {
                    pDataColumn.Unique = true;//字段值是否唯一 
                }
                //字段值是否允许为空 
                pDataColumn.AllowDBNull = pField.IsNullable;
                //字段别名 
                pDataColumn.Caption = pField.AliasName;
                //字段数据类型 
                pDataColumn.DataType = System.Type.GetType(ParseFieldType(pField.Type));
                //字段默认值 
                pDataColumn.DefaultValue = pField.DefaultValue;
                //当字段为String类型时设置字段长度 
                if (pField.VarType == 8)
                {
                    pDataColumn.MaxLength = pField.Length;
                }
                //字段添加到表中 
                pDataTable.Columns.Add(pDataColumn);
                pField = null;
                pDataColumn = null;
            }
            return pDataTable;
        }

        //判断FeatureLayer中FeatureClass的类型（点、线、面）
        public static string getShapeType(ILayer pLayer)
        {
            IFeatureLayer pFeatLyr = (IFeatureLayer)pLayer;
            switch (pFeatLyr.FeatureClass.ShapeType)
            {
                case esriGeometryType.esriGeometryPoint:
                    return "Point";
                case esriGeometryType.esriGeometryPolyline:
                    return "Polyline";
                case esriGeometryType.esriGeometryPolygon:
                    return "Polygon";
                default:
                    return "";
            }
        }

        public static string ParseFieldType(esriFieldType fieldType)
        {
            switch (fieldType)
            {
                case esriFieldType.esriFieldTypeBlob:
                    return "System.String";
                case esriFieldType.esriFieldTypeDate:
                    return "System.DateTime";
                case esriFieldType.esriFieldTypeDouble:
                    return "System.Double";
                case esriFieldType.esriFieldTypeGeometry:
                    return "System.String";
                case esriFieldType.esriFieldTypeGlobalID:
                    return "System.String";
                case esriFieldType.esriFieldTypeGUID:
                    return "System.String";
                case esriFieldType.esriFieldTypeInteger:
                    return "System.Int32";
                case esriFieldType.esriFieldTypeOID:
                    return "System.String";
                case esriFieldType.esriFieldTypeRaster:
                    return "System.String";
                case esriFieldType.esriFieldTypeSingle:
                    return "System.Single";
                case esriFieldType.esriFieldTypeSmallInteger:
                    return "System.Int32";
                case esriFieldType.esriFieldTypeString:
                    return "System.String";
                default:
                    return "System.String";
            }
        }

        //高亮显示在属性表中选中的元素
        public void gridControl1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (this.gridControl1.DataSource != null)
                {
                    if (this.gridView1.SelectedRowsCount == 1)
                    {
                        try
                        {
                            DataRow pRow = this.gridView1.GetDataRow(this.gridView1.GetSelectedRows()[0]);
                            ITable pTable = m_Layer as ITable;
                            int tempIndex = attributeTable.Columns.IndexOf(pTable.OIDFieldName);
                            int fid = Convert.ToInt32(pRow[tempIndex]);
                            IFeatureLayer pFeatureLayer = m_Layer as IFeatureLayer;
                            IFeatureClass pFeatureClas = pFeatureLayer.FeatureClass;
                            IFeature pFeature = pFeatureClas.GetFeature(fid);
                            IGeometry pGeometry = pFeature.ShapeCopy;
                            IEnvelope pEnvelope = pGeometry.Envelope;
                            pEnvelope.Expand(3, 3, true);
                            m_mapControl.Extent = pEnvelope;
                            m_mapControl.Map.ClearSelection();
                            m_mapControl.Map.SelectFeature(m_Layer, pFeature);
                            m_mapControl.ActiveView.Refresh();
                        }
                        catch
                        {

                        }
                    }
                }
            }
        }


    }
}
